<?php

class PapiWS_Model_AffineTransformation {

	public $currentMatrix = array(1,0,0,1,0,0);

	public function __construct( $angle = 0, $dx = 0, $dy = 0)
	{
		if ( $angle != 0 ) 
			$this->rotate( $angle );
		if ( $dx != 0 || $dy != 0 )
			$this->translate( $dx, $dy );
	}

	public function translate( $dx, $dy ) {
		$translation = array( 1, 0, 0, 1, $dx, $dy);
		$this->apply( $translation );
	}

	public function rotate($angle) {

		$angleInRadians = $angle * M_PI / 180.0;
		$sx = cos($angleInRadians);
		$rx = sin($angleInRadians);
		$ry = -sin($angleInRadians);
		$sy = cos($angleInRadians);
		$tx = 0;
		$ty = 0;

		$rotation = array( $sx, $rx, $ry, $sy, $tx, $ty);

		$this->apply( $rotation );
	}

	public function scale( $sx, $sy = null ) {
		if ( $sy == null )
			$sy = $sx;

		$scale = array($sx, 0, 0, $sy, 0, 0);
		$this->apply( $scale );
	}

	public function apply( $m ) {

		$newmatrix = array();

		$a = $this->currentMatrix;

		$newMatrix[0] = $a[0] * $m[0] + $a[1] * $m[2];
		$newMatrix[1] = $a[0] * $m[1] + $a[1] * $m[3];
		$newMatrix[2] = $a[2] * $m[0] + $a[3] * $m[2];
		$newMatrix[3] = $a[2] * $m[1] + $a[3] * $m[3];
		$newMatrix[4] = $a[4] * $m[0] + $a[5] * $m[2] + $m[4];
		$newMatrix[5] = $a[4] * $m[1] + $a[5] * $m[3] + $m[5];

		$this->currentMatrix = $newMatrix;
	}

	public function getCurrentMatrix() 
	{
		return array(
			'sx' => $this->currentMatrix[0],
			'rx' => $this->currentMatrix[1],
			'ry' => $this->currentMatrix[2],
			'sy' => $this->currentMatrix[3],
			'tx' => $this->currentMatrix[4],
			'ty' => $this->currentMatrix[5],
		);
	}



	public static function getRotationMatrix( $angle )
	{
		$angleInRadians = $angle * M_PI / 180.0;
		$sx = cos($angleInRadians);
		$rx = sin($angleInRadians);
		$ry = -sin($angleInRadians);
		$sy = cos($angleInRadians);
		$tx = 0;
		$ty = 0;
		return array( $sx, $rx, $ry, $sy, $tx, $ty);
	}

	public static function getTranslationMatrix( $tx, $ty )
	{
	}

}
